package com.itown.expo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.itown.expo.controller.base.MyBaseCommandController;
import com.itown.expo.model.RecordCodes;

public class RecordCodeEditController extends MyBaseCommandController {

	@Override
	protected ModelAndView handleInner(HttpServletRequest request,
			HttpServletResponse response, Object command) {
		RecordCodes code = (RecordCodes) command;
		code.setCode(code.getType() + code.getIdent());
		List<RecordCodes> list = getServiceContainer().getSettingService()
				.findRecordCodeByCode(code.getCode());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("appPrefix", getAppPrefix());
		if (code.getId() == null) {
			// 新增
			if (list.size() != 0) {
				code.setErrorInfo("添加新纪录失败,此备案号已存在!");
				map.put("code", code);
				return new ModelAndView(getFailureView(), "map", map);
			}
			code = getServiceContainer().getSettingService().saveRecordCode(
					code);
		} else {
			// 修改
			if (list.size() == 1 && !list.get(0).getId().equals(code.getId())) {
				code.setErrorInfo("修改记录失败,此备案号和别的记录重复!");
				map.put("code", code);
				return new ModelAndView(getFailureView(), "map", map);
			}
			getServiceContainer().getSettingService().updateRecordCode(code);
		}
		return new ModelAndView(new RedirectView("RecordCodeSearch.do?id="
				+ code.getId()), "map", map);
	}

}